package crm.controller;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Timestamp;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import crm.daoInterfaces.CustomerInfoDao;
import crm.daoInterfaces.FeedbackDao;
import crm.daoInterfaces.FollowUpActionDao;
import crm.daoInterfaces.InfoSourceDao;
import crm.daoInterfaces.InquiryStateDao;
import crm.daoInterfaces.LeadsDao;
import crm.daoInterfaces.PriorityDao;
import crm.daoInterfaces.ProductDao;
import crm.daoInterfaces.SalesPersonDao;
import crm.dbhandelling.Connections;
import crm.dto.Feedback;
import crm.dto.InfoSource;
import crm.dto.InquiryState;
import crm.dto.Leads;
import crm.dto.Priority;
import crm.dto.Product;
import crm.dto.SalesPerson;
import crm.implementor.CustomerInfoImp;
import crm.implementor.FeedbackImp;
import crm.implementor.FollowUpActionImp;
import crm.implementor.InfoSourceImp;
import crm.implementor.InquiryStateImp;
import crm.implementor.LeadsImp;
import crm.implementor.PriorityImp;
import crm.implementor.ProductImp;
import crm.implementor.SalesPersonImp;
import crm.model.CustomerInfo;
import crm.model.FollowUpAction;
import crm.utility.AppUtility;
import crm.utility.ViewUtilites;
import crm.view.leeds.CustomerInfoPanel;
import crm.view.leeds.EnquiryFormView;
import crm.view.leeds.OfficeUsePanel;
import crm.view.leeds.RequirementsPanel;
import crm.viewframework.Validater;






@SuppressWarnings("unused")
public class EnquiryFormController implements ActionListener{
	private EnquiryFormView view;
	private CustomerInfo modelcustomer;
	private Leads modelead;
	private Feedback modelfeedback;
	private FollowUpAction followupAction;
	
	

	public EnquiryFormController() {
	
	}
	
	


	public EnquiryFormController(EnquiryFormView view, CustomerInfo modelcust,
			Product modelprod, InfoSource modelinfo, Leads modelenq,
			Feedback modelfee, InquiryState modelInquiryState,
			SalesPerson modelattendedBy, FollowUpAction followupAction,
			Priority priority) throws Exception 
	{
		super();
		this.view = view;
		this.modelcustomer = modelcust;
		this.modelead = modelenq;
		this.modelfeedback = modelfee;
		this.followupAction = followupAction;
		view.actionListener(this);
		
		AppUtility.setComboAtten(view.getOfficeUsePanel().getComboBoxAttendedBy());
		AppUtility.setComboReq(view.getRequirements().getComboBoxRequirement());
		AppUtility.setComboPriority(view.getOfficeUsePanel().getComboBoxPriority());
		AppUtility.setComboInfo(view.getRequirementsPanel().getComboBoxInformationBy());
		AppUtility.setComboStatus(view.getOfficeUsePanel().getComboBoxStatus());
		}

	
	
	public void reactOnSave() throws Exception
	{
		
		
		Connection con = null;
		con=Connections.getMyConnection();
		
		
		try
		{
			// Save in Customer Id get the required lead
			int custId=this.saveInCustomerInfo();
			//Save in Feed Back 
			saveInFeedBack(custId);
			// save in leads get the genrated enqiry Id
			int enquiryId=saveInLeeds(custId);
			// save in follow Up Actions
			saveInFollowUpActions(enquiryId);
			JOptionPane.showMessageDialog(null, "Data successfully added");
		}
		catch(SQLIntegrityConstraintViolationException e)
		{
			JOptionPane.showMessageDialog(null, "Name already exist, please use another one");
			e.printStackTrace();
			con.rollback();
		}
		
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Data not successfully added,Please try again !");
			con.rollback();
			e.printStackTrace();
		}
		
		con.setAutoCommit(true);
		con.commit();
		
			
	}

	private int saveInCustomerInfo() throws Exception
	{
		// Get required data to be inserted from view
		CustomerInfoPanel panelCustInfo=view.getCustomerInfo();
		String name= panelCustInfo.getTextFieldName().getText();
		String company=panelCustInfo.getTextFieldCompany().getText();
		String address=panelCustInfo.getTextAreaAddress().getText();
		String email=panelCustInfo.getTextFieldEmail().getText();
		double ph=Double.parseDouble(panelCustInfo.getTextFieldPhone().getText());
		
		//Create the model
		modelcustomer=new CustomerInfo(0,name, address, company, email, ph);
		CustomerInfoDao customerInfoImplemetor=new CustomerInfoImp();
		customerInfoImplemetor.add(modelcustomer);
		
		//Get and return  the auto genrated key
		int custId=customerInfoImplemetor.getAutoGenratedKey();
		return custId;
		
		
	}
	
	private void saveInFeedBack(int custId) throws Exception
	{
		RequirementsPanel panelReq=view.getRequirements(); 
		String feedback=panelReq.getTextAreaFeedback().getText();
		FeedbackDao f=new FeedbackImp();
		modelfeedback=new Feedback(custId, feedback);
		f.add(modelfeedback);
	}
	
	
	private int saveInLeeds(int custId) throws Exception
	{
		// Get required data to be inserted from view
		OfficeUsePanel panelOffice=view.getOfficeUse();
		RequirementsPanel panelReq=view.getRequirementsPanel();
		
		String productName=panelReq.getComboBoxRequirement().getSelectedItem().toString();
		//double minBudget=Double.parseDouble(panelReq.getTfbudget().getText());
		//double maxBudget=Double.parseDouble(panelReq.getTfmaxBudget().getText());
		double minBudget=1000;
		double maxBudget=5000;
		
		String infoSourceName=panelReq.getComboBoxInformationBy().getSelectedItem().toString();
		String reference=panelReq.getComboBoxRequirement().getSelectedItem().toString();
		Date dates=ViewUtilites.convert(view.getTfDate().getText());
		String stateName=panelOffice.getComboBoxStatus().getSelectedItem().toString();
		String priorityName=panelOffice.getComboBoxPriority().getSelectedItem().toString();
		
		// Get the codes specifec to the values
		String prodcode=AppUtility.getProductCode(productName);
		int sourceCode=AppUtility.getInfoSourceId(infoSourceName);
        int stateId=AppUtility.getImquiryStateId(stateName);
		//Add in database
		LeadsDao leadimp=new LeadsImp();
		modelead=new Leads(0, custId, minBudget, sourceCode, reference, dates, prodcode, stateId, priorityName, maxBudget);
		//modelead=new Leads(0, custId, minBudget, sourceCode, reference, dates, prodcode, stateId, priorityName);
		leadimp.add(modelead);
		return leadimp.getAutoGenratedKey();
		
	}
	
	
	private void saveInFollowUpActions(int enquiryId) throws Exception
	{
         OfficeUsePanel panelOffice=view.getOfficeUse();
		 
         //Data from view 
         String comm=panelOffice.getTextAreaComments().getText();
		 String attendedBy=panelOffice.getComboBoxAttendedBy().getSelectedItem().toString();
		 Timestamp t=ViewUtilites.getTime();
		 String stateName=panelOffice.getComboBoxStatus().getSelectedItem().toString();
		 Date dates=ViewUtilites.convert(view.getTfDate().getText());
		 int idSalesPerson= AppUtility.getSalesPersonId(attendedBy);
		
		// add the data
		FollowUpActionDao dao = new FollowUpActionImp();
		followupAction=new FollowUpAction(enquiryId, 1, idSalesPerson, comm, dates, t,1);
		dao.add(followupAction);
		
	}
	

	@Override
	public void actionPerformed(ActionEvent ar) 
	{
		String k=ar.getActionCommand();
		if(k.contains("Save"))
		{
			try 
			{
				
				if(validates())
				{
				  reactOnSave();
				  refresh();
				  
				}
				else
					JOptionPane.showMessageDialog(null,"EMPTY FIELD NOT ALLOWED");
			} catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
		
		if(k.contains("Cl"))
		{
			
			ViewUtilites.makeDateComponent(view.getTfDate());
		}
		
		if(k.contains("Sms"))
		{
			
		}
		
		if(k.contains("Mail"))
		{
			
		}
		
		if(k.contains("Print"))
		{
			
		}
	}
	
	private boolean validates()
	{
		Validater validates = new Validater(view.getOfficeUsePanel());
		String office=validates.validateForEmpty();
		
		validates = new Validater(view.getRequirementsPanel());
		String requirement=validates.validateForEmpty();
		
		
		validates = new Validater(view.getCustomerInfoPanel());
		String customer=validates.validateForEmpty();
		
		validates = new Validater(view);
		String all=validates.validateForEmpty(); 
       
		
		if (office.equals("")&& requirement.equals("")&&customer.equals("")&&all.equals(""))
			return true;
		
		
		 
		
		 
		 return false;
		
		
	}
	
	private void refresh()
	{
		 Validater validates = new Validater(view.getOfficeUsePanel());
		 validates.refresh();
		 validates = new Validater(view.getRequirementsPanel());
		 validates.refresh();
		 validates = new Validater(view.getCustomerInfoPanel());
		 validates.refresh();
		
		
		
	}
	
	

}
